<?php
// the core functions
// static
class Magnum
{
    // import holder
    static protected $_imports = array();

    // app dirs...
    static protected $_dirs = array();


    /**
     * get the dir by key
     * @param str $key the key to get dir
     * @param str $path the path, if null, return the dir by key...
     * @param str dir path...
     */
    static public function dir($key, $path = null)
    {
        if (empty($path)) {
            if (isset(self::$_dirs[$key])) {
                return self::$_dirs[$key];
            }
            var_dump(self::$_dirs);
            throw new Exception('DIR [' . $key . '] DOESNOT EXIST');
        }

        // otherwise, set it...
        self::$_dirs[$key] = $path;

    }// end dir

    /**
     * main function to boot up
     * @param str $view class name of view - so custom view can be used, default to base view
     * @param str $gethandler handler for get
     * @param str $posthandler handler for post
     * @param bool $log log and debug?
     * @param str $mainTemplate the main template, normally site.php
     * @return int 1 for good, 0 for bad
     */
    static public function Main($view = 'Site_View', $gethandler = 'Magnum_Handlers_Get', $postHandler = 'Magnum_Handlers_Post', $log = false, $mainTemplate = 'site.php')
    {
        // import stack manager
        Magnum::importcore('utility/stack/manager');

        if ($log) {
            Magnum::importcore('Magnum_Log');
            Magnum_Log::start();
        }

        // log
        $details = array(
            'class' => __class__,
            'func' => __function__,
            'params' => func_get_args()
        );

         // defaults...
        if (empty($view)) {
            $view = 'Site_View';
        } else {
            if (!class_exists($view))
                throw new Magnum_Exception('View class [' . $view . '] is invalid');
        }

        if (empty($gethandler)) {
            $gethandler = 'Magnum_Handlers_Get';
        } else {
            if (!class_exists($gethandler))
                throw new Magnum_Exception('Get Handler class [' . $gethandler . '] is invalid');
        }

        if (empty($postHandler)) {
            $postHandler = 'Magnum_Handlers_Post';
        } else {
            if (!class_exists($postHandler))
                throw new Magnum_Exception('Post Handler class [' . $postHandler . ']  is invalid');
        }

        // init control with view
        __log('Initializing Magnum Controller', 'core', $details);

        try {
            $ctrl = new Magnum_Control($view, $gethandler, $postHandler);
            $ctrl->getView()->render($mainTemplate);

            // log
            __log('Process finishes successfully', 'core', $details);
            // report
            Magnum_Log::_report();
            return 1;
        } catch (Exception $e) {
            require_once self::dir('THEMEDIR') . 'views/404.php';
            // log
            __log('Process finishes with error', 'core', $details, 1);
            // report
            Magnum_Log::_report();
            return 0;
        }

    }// end main


    /**
     * if internal error...
     */
    static public function e_handle($e)
    {
        if ($e instanceof Magnum_Exception) {
            require_once self::dir('APPCORE') . 'views/error.php';
        }

    }// end e_handle


    /**
     * use a function or file or name space
     * @param $path   path or name
     * @param $isCore if true, it's under _core
     * @param $isTheme if true, under theme/dir
     * @param $once if true, only once
     * @return void
     */
    static public function import($path, $isCore = true, $isTheme = false, $once = true)
    {
        // check if it's in holder already...
        $_key = serialize(array($path, $isCore, $isTheme));

        if (isset(self::$_imports[$_key])) {
            // already in!
            return;
        }

        // interprete path
        $path = strtolower($path);
        if (strpos($path, '_') !== false && strpos($path,'/') === false) {
            // replace to make perfect...
            $path = str_replace('_', '/', $path);
            if (strpos($path, 'magnum') !== false) {
                // it's core
                $path = self::dir('APPCORE') . str_replace('magnum/', '', $path);
            } elseif ($isTheme) {
                // add theme path...
                $path = self::dir('THEMEDIR') . $path;
            } else {
                $path = self::dir('APPEXT') . $path;
            }

        } else {
            if ($isCore) {
                $path = self::dir('APPCORE') . $path;
            } elseif ($isTheme) {
                // add theme path...
                $path = self::dir('THEMEDIR') . $path;
            } else {
                // must be in extended...
                $path = self::dir('APPEXT') . $path;
            }
        }

        $path .=  '.php';

        // otherwise... add it in.
        self::$_imports[$_key] = $path;

        // test if exists...
        if (!file_exists($path)) {
            throw new Magnum_Exception('Magnum::using(' . $path . ') - File doesn\'t exist.');
        }

        if ($once) {
            require_once $path;
        } else {
            include $path;
        }

    }// end use


    /**
     * use core path...
     * @param $path
     * @return void
     */
    static public function importcore($path, $once = 1)
    {
        return self::import($path, true, false, $once);

    }// end importcore


    /**
     * use core path...
     * @param $path
     * @return void
     */
    static public function importext($path, $once = 1)
    {
        return self::import($path, false, false, $once);

    }// end importext


    /**
     * import from theme directory
     */
    static public function importtheme($path, $once = 1)
    {
        return self::import($path, false, true, $once);

    }// end importtheme

}// Magnum

/**
 * internal app exceptions
 */
class Magnum_Exception extends exception
{
    public function __construct($message, $code = null)
    {
        parent::__construct('MAGNUM::INTERNAL APP EXCEPTION::' . $message, $code);

    }// end __construct

}// end Magnum_Exception
?>